import { Component, OnInit } from '@angular/core';
import { WebsocketService } from '../../../services/websocket.service';
import { Router } from "@angular/router";
import { ModalController, ActionSheetController } from '@ionic/angular';
import { PopoverComponent } from '../../components/popover/popover.component';
import { LoginInfoService } from '../../../services/login-info.service';
import { UpphotoService } from '../../../services/upphoto.service';
import { commService } from '../../../services/comm.service';
import { DomSanitizer } from '@angular/platform-browser';
import { HttpService } from '../../../services/http.service';
import { BaseUiService } from '../../../services/base-ui.service';

@Component({
  selector: 'app-sanfanvideo',
  templateUrl: './sanfanvideo.page.html',
  styleUrls: ['./sanfanvideo.page.scss'],
})
export class SanfanvideoPage implements OnInit {
  slideOpts = {
    effect: "flip", //轮播效果
    autoplay: {
      delay: 4000
    },
    loop: false
  };
  public tabIndex:any = '0' //点击tabs
  public htImg:any = [] //合同公证的图片列表
  public isShowimg:boolean = false //图片展示的false
  public roomId:any //存下的公证员的房间ID
  public signatureImg:any //签名存下的码值
  public materialContent = [] //上传材料的图片
  public commissionContent:any //草拟ht内容
  public xwblContent:any //草拟ht内容
  public orderInfo:any //获取的订单的详情
  public htInfo:any = {  //合同公证信息
    jia:{
      name:'',
      gender:'',
      idCard:'',
      address:'',
      mobile:'',
    },
    jiaCompany:{
      companyName:'',
      statutoryPerson:'',
      statutoryMobile:'',
      companyAdd:'',
    },
    yi:{
      name:'',
      gender:'',
      idCard:'',
      address:'',
      mobile:'',
    },
    yiCompany:{
      companyName:'',
      statutoryPerson:'',
      statutoryMobile:'',
      companyAdd:'',
    },
  }
  public gzInfo:any = { //公证内容信息
    yongtu:'',
    area:'',
    lang:'',
    gongzhengValue:'',
    cailiaoValue:'',
  } 
  public jftzContent = {
    address: "",//发证地点
    gzf: 0,//公证费用
    sxf: 0,//摄像费用
    qtf: 0,//其他费用
    smf: 0,//上门服务费
    flf: 0,//法律服务费
    replayFlag: false
  };
  constructor(
    public wsCoket: WebsocketService,
    public modalController: ModalController,
    public LoginInfoService: LoginInfoService,
    public actionSheetController: ActionSheetController,
    public baseUiService:BaseUiService,
    public router: Router,
    public commService: commService,
    public HttpService: HttpService,
    public upphotoService: UpphotoService,
    public sanitizer: DomSanitizer,
  ) { }

  ngOnInit() {
    this.orderInfo= JSON.parse(window.localStorage.getItem("orderInfo"))
    this.roomId= this.LoginInfoService.getlocal('orderInfo').roomId
    try{
      this.commService.initRoom(this.roomId,Math.floor(Math.random()*10000));
    }catch(e){
          console.log("123")
    }
    this.wsCoket.getMessage().subscribe(data => {
      console.log("-------------------")
      console.log(data.code)
      console.log(data)
      if(data != '连接成功'){
        if(data.code == '00'){
          this.htInfo = data.info
        }else if(data.code == '001'){
          this.gzInfo = data.info
        }else if(data.code == '101'){
          //申请人信息表、受理通知单、告知书
          this.iconclick()
          this.htImg = data.info
          this.isShowimg = true
        }else if(data.code == '102'){
          //签字
          this.isShowimg = false;
          this.iconclick()
          this.presentPopover('102')
        }else if(data.code == '500'){
          //上传材料
          this.tabIndex = '1'
        }else if(data.code == '660'){
          //HTML文本
          this.tabIndex = '2'
          this.commissionContent = this.sanitizer.bypassSecurityTrustHtml(data.info);
        }else if(data.code == '511'){
          //HTML文本
          this.tabIndex = '3'
          this.xwblContent = this.sanitizer.bypassSecurityTrustHtml(data.info);
        }else if(data.code == '661'){
          //HTML文本的 图片
          this.iconclick()
          
          this.htImg = data.info
          this.isShowimg = true
        }else if(data.code == '700'){
          //第二次签字
          this.isShowimg = false;
          this.iconclick()
          this.presentPopover('700')
        }else if(data.code == '666'){
          //签字后合同的图片
          this.iconclick()
          this.htImg = data.info
          this.isShowimg = true
        }else if (data.code == "502") {
          //缴费通知
          this.iconclick()
          this.tabIndex = "4";
        }else if (data.code == '023') {
          this.iconclick()
          this.tabIndex = "4";
          this.jftzContent.address = data.info;
        }else if (data.code == '025') {
          this.iconclick()
          this.tabIndex = "4";
          this.jftzContent.gzf = data.info;
        }else if (data.code == '026') {
          this.iconclick()
          this.tabIndex = "4";
          this.jftzContent.flf = data.info;
        }else if (data.code == '027') {
          this.iconclick()
          this.tabIndex = "4";
          this.jftzContent.smf = data.info;
        }else if (data.code == '028') {
          this.iconclick()
          this.tabIndex = "4";
          this.jftzContent.sxf = data.info;
        }else if (data.code == '029') {
          this.iconclick()
          this.tabIndex = "4";
          this.jftzContent.qtf = data.info;
        }else if (data.code == '110') {
          //询问笔录查看
          this.iconclick()
          this.htImg = data.info
          this.isShowimg = true
        }else if (data.code == '106') {
          //缴费通知单查看
          this.iconclick()
          this.htImg = data.info
          this.isShowimg = true
        }else if (data.code == '105') {
          //缴费通知单签字
          this.isShowimg = false;
          this.iconclick()
          this.presentPopover('105')
        }else if (data.code == '300') {
          //去缴费
          this.iconclick()
          this.replay()
        }else if (data.code == '107') {
          //全部预览
          this.iconclick()
          this.htImg = data.info
          this.isShowimg = true
        }else if (data.code == '400') {
          //关闭
          this.baseUiService.showToast('关闭此次视频公证','customblue','top');
          this.router.navigate(['/tabs/tab2']);
          this.wsCoket.closeWebSocket();
          this.commService.exitRoom();
        }
      }
    })
  }
  //tab切换
  tabClick(index:any) {
    switch (index) {
      case "0":
        this.tabIndex = '0';
        break;
      case "1":
        this.tabIndex = '1';
        break;
      case "2":
        this.tabIndex = '2';
        break;
      case "3":
        this.tabIndex = '3';
        break;
      case "4":
        this.tabIndex = '4';
        break;
    }
  }

  //关闭轮播图
  iconclick() {
    this.htImg = []
    this.isShowimg = false
  }

  //签字
  async presentPopover(num:any) {
    // let dom=document.getElementById("canvas")
    // if(!!dom){
    //     return false
    // }
    const modal = await this.modalController.create({
      component: PopoverComponent,
      cssClass:'videoQz'
    });
    await modal.present();
    //监听销毁的事件，此时data存的是模态窗口页面销毁时候的值
    const { data } = await modal.onDidDismiss();
    console.log(data)
    this.signatureImg = data.result.msg
    if (data.result.info) {
      this.upphotoService.Uploading(this.signatureImg, 'must').then(res => {
        
        console.log(res,'++++')
        if(num == '102'){
          this.wsCoket.sendMessage(this.sendPCmessage(res[0]['filePath'], '020'))
        }else if(num == '700'){
          this.wsCoket.sendMessage(this.sendPCmessage(res[0]['filePath'], '780'))
        }else if(num == '105'){
          this.wsCoket.sendMessage(this.sendPCmessage(res[0]['filePath'], '205'))
        }
      })

    }
  }

  //向PC端发送消息
  sendPCmessage(message: any, code: any) {
    let info = {
      code: code,
      info: message,
      userId:this.roomId,
      formUserId:this.LoginInfoService.getInfo().idCard
    }
    return info
  }

  //底部弹出上传材料
  async presentActionSheet() {
    const actionSheet = await this.actionSheetController.create({
      header: '上传材料',
      buttons: [{
        text: '相册上传',
        icon: 'image-outline',
        handler: () => {
          this.commService.picture(400, 40).subscribe(res => {
            this.getPirture(res)
          })
        }
      }, {
        text: '关闭',
        icon: 'close',
        role: 'cancel',
        handler: () => {
        }
      }]
    });
    await actionSheet.present();
  }

  //上传材料的处理
  getPirture(info: any) {
    this.upphotoService.Uploading(info).then(res1 => {
      console.log("同步数据")
      this.materialContent = [...this.materialContent, ...res1]
      // setTimeout(()=>{
      //   this.cd.detectChanges();
      // },200)
      this.wsCoket.sendMessage({
        code: '010',
        info: [{
          annexFileList: res1[0]['unitGuid'],
          imgPathList: res1[0]['filePath']
        }],
        userId:this.roomId,
      })
    })
  }

  //支付
  async replay() {
    const actionSheet = await this.actionSheetController.create({
      header: '支付',
      cssClass:"relay",
      buttons: [{
        text: '支付宝支付',
        role: 'share',
        icon: 'iconfont icon-zhifubao1',
        handler: () => {
          this.doSign();
        }
      }, {
        text: '微信支付',
        role: 'share',
        icon: 'iconfont icon-weixinzhifu1',
        handler: () => {
          this.doSign();
        }
      }, {
        text: '关闭',
        icon: 'close',
        role: 'cancel',
        handler: () => {
        }
      }]
    });
    await actionSheet.present();
  }

  /**
   * **支付宝 付款接口
   * @memberOf doSign
  * */
 doSign(){
  let param={
    outTradeNo:this.LoginInfoService.getlocal('orderInfo').orderNo 
  }
  this.HttpService.doSign(param).then(res=>{  
    if(res['code']=="200"){
      this.commService.aliPay(res['item']).subscribe(res=>{
        if(res.trim() =="5001"){
            this.baseUiService.showToast('支付失败','customblue','top');
            this.wsCoket.sendMessage(this.sendPCmessage("","3333"));
            // this.doVideologSetState("91");
          }else{
            this.baseUiService.showToast('支付成功','customblue','top');
            this.wsCoket.sendMessage(this.sendPCmessage("","301"));
            // this.doVideologSetState("65");
          }
      })
    }
  })
  }
  doVideologSetState(code){
    console.log("doVideologSetState",code);
    let param={
        unitGuid:this.LoginInfoService.getlocal('orderInfo').unitGuid ,
        notaryState: code
    }
    this.HttpService.doVideologSetState(param).then(res=>{  
      if(res['code']=="200"){
        
      }
    })
  }
}
